/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.sale.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dian.common.enums.ValidEnum;
import com.dian.common.utils.*;
import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.modules.enums.sale.ProbHead_OrderStateEnum;
import com.dian.modules.inv.service.GoodsStockService;
import com.dian.modules.inv.vo.GoodsStockVO;
import com.dian.modules.sale.vo.ProbHeadExportVO;
import com.dian.modules.sale.vo.ProbLineExportVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dian.common.exception.RRException;
import com.dian.common.utils.Date;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections.CollectionUtils;
import com.dian.common.server.CommonService;
import com.dian.modules.sale.dao.ProbHeadDao;
import com.dian.modules.sale.entity.ProbHeadEntity;
import com.dian.modules.sale.service.ProbHeadService;
import com.dian.modules.sale.service.ProbLineService;
import com.dian.modules.sale.entity.ProbLineEntity;

/**
 * 预订单服务实现类
 *
 * @author xiaolai
 * @email xiaolai@9dyun.cn
 * @date 2019-06-10 23:04:30
 */
@Service("probHeadService")
public class ProbHeadServiceImpl extends ServiceImpl<ProbHeadDao, ProbHeadEntity> implements ProbHeadService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public CommonService commonService;

    @Autowired
    public ProbLineService probLineService;

    @Autowired
    public GoodsStockService goodsStockService;

    /**
     * 预订单分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<ProbHeadEntity> page = this.page(new Query<ProbHeadEntity>().getPage(params),getQueryWrapper(params) );
        return new PageUtils(page);
    }

    /**
    *  预订单新增
    * @param probHeadEntity
    * @return
    */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(ProbHeadEntity probHeadEntity) {

        probHeadEntity.setProbNo(commonService.getCode(ProbHeadEntity.class));
        probHeadEntity.setProbDate(new Date());
        probHeadEntity.setProbMonth(new Date().toText2());
        probHeadEntity.setIsSale(ValidEnum.NO.getValue());

        //数据完整性校验
        this.paramsCheck(probHeadEntity,AddGroup.class);

        //设置编码，基础默然初始化数据设置
        //probHeadEntity.setOrderNo(commonService.getOrderCode("XSD"));
        //probHeadEntity.setOrderDate(new Date());


        //保存主表
        this.save(probHeadEntity);

        //保存从表
        if (CollectionUtils.isNotEmpty(probHeadEntity.getProbLineEntityList())) {
            List<ProbLineEntity> detailList = probHeadEntity.getProbLineEntityList();
            for (ProbLineEntity detail : detailList) {
                detail.setProbId(probHeadEntity.getId());
            }
            probLineService.saveBatch(probHeadEntity.getProbLineEntityList());
        }
        return true;
    }

    /**
     *预订单更新
     * @param probHeadEntity
     * @return
     */
    @Override
    public boolean updateInfo(ProbHeadEntity probHeadEntity) {

        //修改状态校验
        this.updateCheck(probHeadEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(probHeadEntity, UpdateGroup.class);

        //更新主表
        this.updateById(probHeadEntity);

        //更新从表
        probLineService.updateInfo(probHeadEntity);


        return true;
    }

    /**
     *预订单删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteInfo(Long id) {

        //删除状态校验
        this.deleteCheck(id);

        //更新从表
        probLineService.deleteInfo(id);

        //更新主表
        this.remove(new QueryWrapper<ProbHeadEntity>().eq("id",id));

        return true;
    }

    /**
     * 预订单详情
     * @param id
     * @return
     */
    @Override
    public ProbHeadEntity getInfo(Long id) {
        ProbHeadEntity probHeadEntity =getById(id);
        List<ProbLineEntity> lineList=probLineService.queryLineList(id);
        probHeadEntity.setProbLineEntityList(lineList);
        return probHeadEntity;
    }

    /**
     * 预订单审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        ProbHeadEntity probHeadEntity =this.getById(id);
        checkCheck(probHeadEntity);
        probHeadEntity.setOrderState(ProbHead_OrderStateEnum.AUDITED.getValue());
        probHeadEntity.setCheckDate(new Date());
        probHeadEntity.setCheckUserId(commonService.getUserId());
        probHeadEntity.setCheckUserName(commonService.getUserName());
        this.updateById(probHeadEntity);



         return true;
    }

    /**
     * 预订单分页导出
     * @param params
     * @return
     */
    @Override
    public List<ProbHeadExportVO> exportList(Map<String, Object> params) {
        List<ProbHeadEntity> list=new ArrayList<>();
        if(!StrUtil.isBlankIfStr(params.get("exprotType"))){
            list= this.page(new Query<ProbHeadEntity>().getPage(params),getQueryWrapper(params)).getRecords();
        }else{
            list= this.list(getQueryWrapper(params));
        }

        List<ProbHeadExportVO> resultList = BeanConverter.convertList(list, ProbHeadExportVO.class);
        // 封装明细
        if(CollectionUtils.isNotEmpty(resultList)){
            for(ProbHeadExportVO probHeadEntity : resultList){
                List<ProbLineEntity> probLineEntityList = probLineService.queryLineList(probHeadEntity.getId());
                probHeadEntity.setProbLineExportVOList(BeanConverter.convertList(probLineEntityList, ProbLineExportVO.class));
            }
        }
        return resultList;
    }

    /**
     * 查询预订单使用库存
     * @param goodsId
     * @return
     */
    public BigDecimal useProQty(Long  goodsId){
        return getBaseMapper().useProQty(goodsId);
    }

    /**
     * 检查是否已转销售订单
     * @param id
     * @return
     */
    @Override
    public boolean checkCreateSaleOrder(Long  id){
        ProbHeadEntity probHeadEntity =getById(id);
        if(probHeadEntity.getIsSale().equals(ValidEnum.YES.getValue())){
            throw new RRException(String.format("[%s] 当前预订订单已生成销售订单,请勿重复生成",probHeadEntity.getProbNo()));
        }
        return true;
    }
    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        ProbHeadEntity probHeadEntity =this.getById(id);
        if(!probHeadEntity.getOrderState().equals(ProbHead_OrderStateEnum.WAITCHECK.getValue())){
            throw new RRException(String.format("[%s] 当前订单非未审核状态,禁止修改",probHeadEntity.getProbNo()));
        }
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(ProbHeadEntity probHeadEntity) {

        if(!probHeadEntity.getOrderState().equals(ProbHead_OrderStateEnum.WAITCHECK.getValue())){
            throw new RRException(String.format("[%s] 当前订单非未审核状态,禁止审核",probHeadEntity.getProbNo()));
        }
    }

    /**
     * 删除状态校验
     *
     * @param
     */
    private void deleteCheck(Long id) {
        ProbHeadEntity probHeadEntity =this.getById(id);
        if(!probHeadEntity.getOrderState().equals(ProbHead_OrderStateEnum.WAITCHECK.getValue())){
            throw new RRException(String.format("[%s] 当前订单非未审核状态,禁止删除",probHeadEntity.getProbNo()));
        }
    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(ProbHeadEntity record, Class<?> cls) {
        ListUtils.setPropertyValue(record.getProbLineEntityList(),"probId",record.getId());

        ValidatorUtils.validateEntity(record, cls);
        if (CollectionUtils.isEmpty(record.getProbLineEntityList())) {
            throw new RRException("预订单明细数据不能为空");
        }
        for (ProbLineEntity probLineEntity : record.getProbLineEntityList()) {
            int index = record.getProbLineEntityList().indexOf(probLineEntity) + 1;
            try {
                ValidatorUtils.validateEntity(probLineEntity, Arrays.asList("probId"), cls);
            }catch (RRException e){
                throw new RRException(String.format("第%s行 预订单明细校验失败<br/>"+e.getMsg(), index));
            }
        }
    }

    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<ProbHeadEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<ProbHeadEntity> queryWrapper=new QueryWrapper<>();
        if(!StrUtil.isBlankIfStr(params.get("probDate"))){
            String purchaseDate=String.valueOf(params.get("probDate"));
            String[] probDateRange=purchaseDate.split("至");
            if(probDateRange.length==2){
                queryWrapper.gt("prob_date",DateUtils.getBeginTimeOfDate(probDateRange[0]));
                queryWrapper.lt("prob_date",DateUtils.getBeginTimeOfDate(probDateRange[1]));
            }else{
                queryWrapper.gt("prob_date",DateUtils.getBeginTimeOfDate(purchaseDate));
            }
        }
       /* if(!StrUtil.isBlankIfStr(params.get("orderNo"))){
            queryWrapper.like("order_no",params.get("orderNo"));
        }*/
        if(!StrUtil.isBlankIfStr(params.get("probNo"))){
            queryWrapper.likeLeft("prob_no",params.get("probNo"));
        }
        queryWrapper.orderByDesc("id");
        return queryWrapper;
    }
}
